<route lang="json5">
{
  style: {
    navigationBarTitleText: '预约信息填写',
    navigationBarTextStyle: 'white', //标题栏字体颜色
    navigationBarBackgroundColor: '#0063AF', //标题栏背景色(纯色)
  },
}
</route>
<template>
  <view class="visitSub w-screen h-screen box-border overflow-auto bg-#fff">
    <view class="w-100% mx-auto">
      <wd-form ref="form" :model="model" :rules="rules">
        <!-- <view class="overflow-hidden bg-#fff">
          <view class="font-bold bg-#E9F3FF px-30rpx py-14rpx text-28rpx">预约时段</view>

          <view class="px-40rpx py-30rpx">
            <wd-cell title-width="0rpx" prop="requestTime">
              <wd-radio-group v-model="model.requestTime" shape="dot" prop inline>
                <wd-radio :value="1"><text class="text-28rpx ml-20rpx">9:00-10:30</text></wd-radio>
                <wd-radio disabled :value="2">
                  <text class="text-28rpx ml-20rpx">10:45-12:00 已预约</text>
                </wd-radio>
                <wd-radio :value="3"><text class="text-28rpx ml-20rpx">14:00-15:30</text></wd-radio>
                <wd-radio :value="4"><text class="text-28rpx ml-20rpx">15:45-17:00</text></wd-radio>
              </wd-radio-group>
            </wd-cell>
          </view>
        </view> -->
        <view class="overflow-hidden bg-#fff">
          <view class="font-bold bg-#E9F3FF px-30rpx py-14rpx text-28rpx">接访内容</view>
          <view class="px-40rpx py-20rpx">
            <wd-cell title="事情描述" vertical prop="content">
              <wd-textarea
                v-model="model.content"
                :maxlength="300"
                :show-word-limit="true"
                placeholder="简要说明市民要反映的主要问题，让检察官对接访内容有初步的了解，如“对某刑事案件判决不服”“反映某行政机关不作为”等。"
              />
            </wd-cell>
            <wd-cell title="诉求期望" vertical>
              <wd-textarea
                v-model="model.desire"
                :maxlength="300"
                :show-word-limit="true"
                placeholder="清晰地阐述市民希望通过此次接访达到的目的，例如要求重新审查案件”“督促相关部门履行职责”等。"
              />
            </wd-cell>
            <view class="mb-20rpx text-24rpx">上传相关材料（选填）：</view>
            <view class="rounded-20rpx">
              <wd-cell>
                <view class="flex flex-col">
                  <view @click="handleFile" class="pos-relative">
                    <view class="w-80px h-80px flex justify-center items-center videoCard">
                      <wd-icon size="35px" color="#B8B8B8" name="add"></wd-icon>
                    </view>
                  </view>
                  <view>
                    <view v-for="(item, index) in model.fileList" :key="index">
                      <text class="mr-30rpx my-20rpx">{{ item.name }}</text>
                      <wd-icon
                        name="delete"
                        size="18px"
                        color="#ec2828"
                        @click="handleDelete(index)"
                      ></wd-icon>
                    </view>
                  </view>
                </view>
              </wd-cell>
            </view>
          </view>
        </view>

        <view class="footer w-80% mx-auto submit-but">
          <wd-button class="bg-#006EFF!" type="primary" size="medium" @click="submitHandler" block>
            提交
          </wd-button>
        </view>
      </wd-form>
    </view>
  </view>
</template>

<script setup lang="ts">
import { FormRules } from 'wot-design-uni/components/w-d-form/src/types'
import { upmInterviewAPI } from '@/service/index/foo'
import { formatTime } from '@/utils/index'
import { useUserStore } from '@/store'
import { useToast, useMessage } from 'wot-design-uni'
import banner from '../../static/images/banner.jpg'
import _ from 'lodash'
const baseUrl = import.meta.env.VITE_SERVER_BASEURL
const message = useMessage()
const userStore = useUserStore()
const form = ref()
const model = reactive<{
  content: string
  desire: string
  files: string[]
  fileList: Record<string, string>[]
  status: number
  businessType: string
  name: string
  phone: string | number
  meetingNumber: string
}>({
  content: '',
  desire: '',
  files: [],
  fileList: [],
  status: 1,
  businessType: 'jieFang',
  name: userStore.userInfo.nickname,
  phone: userStore.userInfo.phone,
  meetingNumber: getMathRandom(),
})
const cameraList = [
  {
    value: 'back',
    name: '后置摄像头',
    checked: 'true',
  },
  {
    value: 'front',
    name: '前置摄像头',
  },
]
const interviewId = ref()
const nickname = null
const rules: FormRules = {
  content: [
    {
      required: true,
      message: '请输入活动细则信息',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入活动细则信息')
        }
      },
    },
  ],
}

const toast = useToast()
const action: string = import.meta.env.VITE_SERVER_BASEURL + '/app-api/infra/file/upload-id'

onLoad((options) => {
  interviewId.value = options.id
})
function getMathRandom() {
  const result = parseInt(Math.random() * 1000000) + 1000000
  return result.toString().slice(0, 6)
}
function handleFile() {
  wx.chooseMessageFile({
    count: 1, // 限制选择的文件数量
    type: 'file', // 非图片和视频的文件,不选默认为all
    extension: ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'], // 此处限制文件类型
    success(res) {
      const tempFilePaths = res.tempFiles
      toast.loading({
        msg: '上传中...',
      })
      // 下面是返回后需要调接口的操作
      const uploadTask = uni.uploadFile({
        url: '/app-api/infra/file/upload-id',
        filePath: tempFilePaths[0].path,
        method: 'POST',
        name: 'file',
        formData: {
          name: tempFilePaths[0].name,
        },
        success: (uploadFileRes) => {
          // 接口返回的数据
          model.fileList.push(tempFilePaths[0])
          const { data } = JSON.parse(uploadFileRes.data)
          model.files.push(data)
          toast.close()
        },
        fail: () => {
          toast.close()
        },
      })
      uploadTask.onProgressUpdate((res) => {
        toast.loading({
          msg: '上传中' + res.progress + '%',
        })
        if (res.progress == 100) {
          toast.close()
        }
      })
    },
  })
}
function handleDelete(index) {
  model.fileList.splice(index, 1)
  model.files.splice(index, 1)
}
const submitHandler = _.debounce(() => {
  handleSubmit()
}, 1000)
function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        message
          .confirm({
            title: '通知',
            msg: '为了通知您审核进度，需要向您推送相关消息',
          })
          .then(() => {
            uni.requestSubscribeMessage({
              tmplIds: ['4RzJ2EHQuMw4vxjRCuEBQ3dvfATdC-2j4sYWie2uBh8'],
              success(res) {
                try {
                  upmInterviewAPI({
                    id: interviewId.value,
                    ...model,
                    fileList: undefined,
                    files: [...model.files],
                    openId: userStore.userInfo.openid,
                  }).then((res) => {
                    if (res.code !== 0) {
                      toast.error({
                        msg: res.msg,
                        duration: 0,
                      })
                    } else {
                      toast.success({
                        msg: '操作成功',
                        duration: 0,
                      })
                    }
                    setTimeout(() => {
                      uni.navigateTo({
                        url: `/pages/visit/visitMsg`,
                      })
                      toast.close()
                    }, 1500)
                  })
                } catch (error) {
                  console.log(error)
                }
              },
              fail: (fail) => {
                console.log(fail, 888)
              },
            })
          })
          .catch(() => {})
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
</script>
<style lang="scss" scoped>
.submit-but {
  ::v-deep .wd-button {
    background: #006eff !important;
  }
}

::v-deep .wd-cell {
  padding: 0 !important;
  background: rgba(0, 0, 0, 0.25);
}

::v-deep .wd-cell__value {
  text-align: left !important;
}

::v-deep .wd-icon {
  color: #aaa8a8;
}

.videoCard {
  background: rgba(0, 0, 0, 0.04);
}

::v-deep .wd-icon-sound {
  margin-right: 20rpx;
}

::v-deep .wd-cell__left {
  flex: none !important;
  margin-right: 5rpx !important;
}

:deep(.wd-radio-group) {
  display: flex;
  flex-direction: column;
  width: max-content;
}

:deep(.wd-radio) {
  text-align: left !important;
  margin-bottom: 20rpx !important;
}

// :deep(.wd-button__text) {
//   color: #fff;
// }
::v-deep .wd-textarea {
  padding: 0 !important;
}

::v-deep .wd-textarea::after,
::v-deep .wd-input::after {
  height: 0 !important;
}

::v-deep .wd-textarea__value,
::v-deep .wd-input__value {
  padding: 20rpx !important;
  background: #f3f4f7 !important;
}

::v-deep .wd-textarea__count,
::v-deep .wd-input__count {
  right: 20rpx !important;
  background: #f3f4f7 !important;
}

::v-deep .wd-cell__wrapper.is-vertical .wd-cell__right {
  margin-top: 0rpx !important;
}
</style>
